package com.enation.app.javashop.seller.api.member;

import com.dag.eagleshop.core.account.model.dto.account.AccountDTO;
import com.dag.eagleshop.core.account.model.dto.member.MemberDTO;
import com.dag.eagleshop.core.account.model.dto.withdraw.ApplyWithdrawReqDTO;
import com.dag.eagleshop.core.account.model.enums.AccountTypeEnum;
import com.dag.eagleshop.core.account.model.enums.WithdrawTypeEnum;
import com.dag.eagleshop.core.account.service.AccountManager;
import com.enation.app.javashop.core.base.SceneType;
import com.enation.app.javashop.core.base.model.vo.SuccessMessage;
import com.enation.app.javashop.core.client.member.ShopClient;
import com.enation.app.javashop.core.client.system.SmsClient;
import com.enation.app.javashop.core.distribution.exception.DistributionErrorCode;
import com.enation.app.javashop.core.member.MemberErrorCode;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.model.dos.WithdrawRecordDO;
import com.enation.app.javashop.core.member.model.dto.WithdrawRecordQueryParam;
import com.enation.app.javashop.core.member.model.vo.ApplyWithdrawVO;
import com.enation.app.javashop.core.member.service.ConnectManager;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.member.service.WithdrawRecordManager;
import com.enation.app.javashop.core.orderbill.service.BillCountManager;
import com.enation.app.javashop.core.shop.model.vo.ShopVO;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 商家提现api
 * @author 孙建
 */

@RestController
@RequestMapping("/seller/members/withdraw")
@Api(description = "商家提现api")
public class WithdrawSellerController {

    protected final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    private WithdrawRecordManager withdrawRecordManager;
    @Autowired
    private BillCountManager billCountManager;
    @Autowired
    private ShopClient shopClient;
    @Autowired
    private ConnectManager connectManager;
    @Autowired
    private MemberManager memberManager;
    @Autowired
    private SmsClient smsClient;
    @Autowired
    private AccountManager accountManager;


    @ApiOperation("提现金额和银行卡查询")
    @PostMapping(value = "/view-withdraw")
    public Map viewWithdraw() {
        Seller seller = UserContext.getSeller();
        if (seller == null) {
            throw new ServiceException(DistributionErrorCode.E1001.code(), DistributionErrorCode.E1001.des());
        }

        // 查询会员
        Member member = memberManager.getModel(seller.getUid());
        // 查询商铺
        ShopVO shop = shopClient.getShop(seller.getSellerId());
        // 查询可提现金额
        BigDecimal withdrawPrice = billCountManager.countPassPrice(seller.getSellerId());
        // 如果结算单可提现金额等于0 说明之前版本账户逻辑已经走完 此时返回虚拟账户余额
        if(withdrawPrice.doubleValue() == 0){
            String accountMemberId = member.getAccountMemberId();
            AccountDTO accountDTO = accountManager.queryByMemberIdAndAccountType(accountMemberId, AccountTypeEnum.MEMBER_MASTER.getIndex());
            withdrawPrice = accountDTO.getBalanceAmount();
        }

        Map<Object, Object> resultMap = new HashMap<>();
        resultMap.put("apply_money", withdrawPrice);
        resultMap.put("bank_name", shop.getBankName());
        resultMap.put("bank_account_name", shop.getBankAccountName());
        resultMap.put("bank_number", shop.getBankNumber());
        String mobile = member.getMobile();
        resultMap.put("mobile", mobile.substring(0, 3) + "****" + mobile.substring(7, 11));
        return resultMap;
    }


    @ApiOperation(value = "发送手机验证码")
    @PostMapping("/sms-code")
    public void smsCode() {
        Seller seller = UserContext.getSeller();
        // 查询会员
        Member member = memberManager.getModel(seller.getUid());
        // 发送验证码
        connectManager.sendCheckMobileSmsCode(member.getMobile());
    }


    @ApiOperation("提现申请")
    @PostMapping(value = "/apply-withdraw")
    public SuccessMessage applyWithdraw(@RequestBody ApplyWithdrawVO applyWithdrawVO) {
        Seller seller = UserContext.getSeller();
        if (seller == null) {
            throw new ServiceException(DistributionErrorCode.E1001.code(), DistributionErrorCode.E1001.des());
        }
        if (applyWithdrawVO == null) {
            throw new ServiceException(DistributionErrorCode.E1011.code(), DistributionErrorCode.E1011.des());
        }
        Double applyMoney = applyWithdrawVO.getApplyMoney();
        //如果提现申请金额值非法
        if (applyMoney <= 0) {
            throw new ServiceException(DistributionErrorCode.E1006.code(), DistributionErrorCode.E1006.des());
        }

        // 查询会员
        Member member = memberManager.getModel(seller.getUid());
        // 校验验证码
        boolean bool = smsClient.valid(SceneType.VALIDATE_MOBILE.name(), member.getMobile(), applyWithdrawVO.getCaptcha());
        if (!bool) {
            throw new ServiceException(MemberErrorCode.E107.code(), "短信验证码错误");
        }

        BigDecimal passPrice = billCountManager.countPassPrice(seller.getSellerId());
        // 如果结算单可提现金额为0 本次申请的流程必须走账户系统
        if(passPrice.doubleValue() == 0){
            String accountMemberId = member.getAccountMemberId();
            AccountDTO accountDTO = accountManager.queryByMemberIdAndAccountType(accountMemberId, AccountTypeEnum.MEMBER_MASTER.getIndex());
            BigDecimal balanceAmount = accountDTO.getBalanceAmount();
            if(applyMoney <= balanceAmount.doubleValue()){
                MemberDTO memberDTO = accountManager.queryMemberById(accountMemberId);
                // 发送到账户系统
                ApplyWithdrawReqDTO applyWithdrawReqDTO = new ApplyWithdrawReqDTO();
                applyWithdrawReqDTO.setAccountId(accountDTO.getId());
                applyWithdrawReqDTO.setAmount(BigDecimal.valueOf(applyMoney));
                applyWithdrawReqDTO.setBankName(applyWithdrawVO.getBankName());
                applyWithdrawReqDTO.setSubBankName("");
                applyWithdrawReqDTO.setCardNo(applyWithdrawVO.getBankNumber());
                applyWithdrawReqDTO.setOpenAccountName(member.getNickname());
                applyWithdrawReqDTO.setMemberId(memberDTO.getId());
                applyWithdrawReqDTO.setMemberName(memberDTO.getMemberName());
                applyWithdrawReqDTO.setWithdrawType(WithdrawTypeEnum.OFFLINE.getIndex());
                applyWithdrawReqDTO.setApplyRemark(applyWithdrawVO.getApplyRemark());
                accountManager.applyWithdraw(applyWithdrawReqDTO);
            }else{
                throw new ServiceException(DistributionErrorCode.E1003.code(), DistributionErrorCode.E1003.des());
            }
        }else{
            // 继续走之前的结算单提现逻辑
            if (applyMoney <= passPrice.doubleValue()) {
                WithdrawRecordDO withdrawRecordDO = new WithdrawRecordDO();
                BeanUtil.copyProperties(applyWithdrawVO, withdrawRecordDO);
                withdrawRecordDO.setMemberId(seller.getUid());
                this.withdrawRecordManager.applyWithdraw(withdrawRecordDO);
            } else {
                throw new ServiceException(DistributionErrorCode.E1003.code(), DistributionErrorCode.E1003.des());
            }
        }
        return new SuccessMessage("已提交申请");
    }


    @ApiOperation("提现记录")
    @GetMapping(value = "/apply-history")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_no", value = "页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "page_size", value = "分页大小", required = true, paramType = "query", dataType = "int"),
    })
    public Page<WithdrawRecordDO> applyHistory(@ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize) {
        Seller seller = UserContext.getSeller();
        if (seller == null) {
            throw new ServiceException(DistributionErrorCode.E1001.code(), DistributionErrorCode.E1001.des());
        }

        // 查询列表
        WithdrawRecordQueryParam withdrawRecordQueryParam = new WithdrawRecordQueryParam();
        withdrawRecordQueryParam.setPageNo(pageNo);
        withdrawRecordQueryParam.setPageSize(pageSize);
        withdrawRecordQueryParam.setSellerId(seller.getSellerId());
        return withdrawRecordManager.list(withdrawRecordQueryParam);
    }


}
